package com.wyf.springbootmybatis;

import com.sun.corba.se.impl.ior.OldJIDLObjectKeyTemplate;
import com.wyf.springbootmybatis.exceptions.ParamsException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理类
 */
@ControllerAdvice // 作为全局异常处理的切面类，交给IOC容器维护
public class GlobalExceptionHandlerResolver {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map<String, Object> exceptionHandler(Exception e) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", "系统异常，请重试");

        // if (e instanceof ParamsException) {
        //     ParamsException p = (ParamsException)e;
        //     result.put("code", p.getCode());
        //     result.put("message", p.getMsg());
        // }

        return result;
    }

    /**
     * 处理特定异常
     */
    @ExceptionHandler(value = ParamsException.class)
    @ResponseBody
    public Map<String, Object> exceptionHandler02(ParamsException p) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", p.getCode());
        result.put("message", p.getMsg());
        return result;
    }

    /**
     * 处理数据校验的异常
     * @param b
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Map<String, Object> exceptionHandler03(BindException b) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", b.getBindingResult().getFieldError().getDefaultMessage());
        return result;
    }
}

